package com.kyivmohyla.kma2.client.presenter.operator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.kyivmohyla.kma2.client.gin.Injector;
import com.kyivmohyla.kma2.client.presenter.Presenter;

public class FileUploadPresenter implements Presenter {

    private final Display display;
    private final Injector injector = Injector.INSTANCE;

    public FileUploadPresenter() {
        this.display = injector.getFileUploadView();
        this.display.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
        this.display.getFormPanel().setMethod(FormPanel.METHOD_POST);
        this.display.getFormPanel().setAction(GWT.getModuleBaseURL() + "FileUploadServlet");
        bind();
    }

    private void bind() {
        display.getImportButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doImport();
            }
        });
    }

    private void doImport() {
        display.getFormPanel().submit();
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

    public Display getDisplay() {
        return display;
    }

    public interface Display {

        FileUpload getFileUpload();

        FormPanel getFormPanel();

        HasClickHandlers getImportButton();

        HasClickHandlers getCancelButton();

        Widget asWidget();
    }
}
